package com.ruoyi.system.controller;

import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import com.ruoyi.common.core.domain.R;
//import com.ruoyi.system.dto.CwPaymentPlanDto;
//import com.ruoyi.system.dto.RequestDetailSfContractSaveDto;
//import com.ruoyi.system.enums.CertificateType;
//import com.ruoyi.system.utils.BeanUtils;
//import com.ruoyi.system.utils.PayMentPlanGenerator;
//import com.ruoyi.system.utils.PhoneFormatCheckUtils;
//import com.ruoyi.system.utils.RegularCheckUtils;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.domain.Contract;
import com.ruoyi.system.domain.FinalStatement;
import com.ruoyi.system.service.FinalStatementDetailService;
import com.ruoyi.system.utils.Doc2Pdf;
import com.ruoyi.system.utils.EmailUtil;
import com.ruoyi.system.utils.PhoneFormatCheckUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.service.IContractService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 收房合同Controller
 *
 * @author zhzaoxian
 * @date 2023-02-24
 */
@RestController
@RequestMapping("/contract")
public class ContractController extends BaseController {
    @Autowired
    private IContractService contractService;

    @Resource
    RemoteFileService FileService;

//    @Resource
//    TencentCOSUtil tencentCOSUtil;
//
//
//    /**
//     * 文件上传
//     * 返回 文件 url
//     */
//    @RequiresPermissions("contract:contract:Myupload")
//    @PostMapping("/Myupload")
//    public R Myupload(MultipartFile file)
//    {
//        String url = tencentCOSUtil.uploadfile(file);
//        return R.ok(url);
//    }

//    /**
    //     * 收房合同录入：下一步 校验合同租约信息等
    //     */
//    @RequestMapping("nextSfContract")
//    @ResponseBody
//    private R nextCfContract(@Validated contract contract, BindingResult bindingResult) {
//        if (contract.getHouseType()==-1) {
//            contract.setHouseType(null);
//        }
//        if(contract.getHouseType()==null) {
//            bindingResult.rejectValue("houseType", "{common.sfHouseTypr.incorrect}");
//        }
//        // 业主证件校验
//        String cardNo = contract.getOwnerIdCard();
//        if (!StringUtils.isEmpty(cardNo)) {
//            if (contract.getCertificateType() == CertificateType.IDCARD.getIndex()
//                    && false == RegularCheckUtils.isIDCardNo(cardNo)) {// 身份证
//                bindingResult.rejectValue("ownerIdCard", "{common.idcard.incorrect}");
//            } else if (contract.getCertificateType() == CertificateType.passport.getIndex()
//                    && false == RegularCheckUtils.isPassport(cardNo)) {// 护照
//                bindingResult.rejectValue("ownerIdCard", "{common.passport.incorrect}");
//            } else if (contract.getCertificateType() == CertificateType.MTPS.getIndex()
//                    && false == RegularCheckUtils.isTBCard(cardNo)) {// 台胞证
//                bindingResult.rejectValue("ownerIdCard", "{common.tbcard.incorrect}");
//            } else if (contract.getCertificateType() == CertificateType.HKMACAOPASS.getIndex()
//                    && false == RegularCheckUtils.isHKMT(cardNo)) {// 港澳台通行证
//                bindingResult.rejectValue("ownerIdCard", "{common.hkmt.incorrect}");
//            }
//        }
//        // 签约人证件校验
//        String cardNo2 = contract.getSignUserIdCard();
//        if (!StringUtils.isEmpty(cardNo2)) {
//            if (contract.getCertificateType() == CertificateType.IDCARD.getIndex()
//                    && false == RegularCheckUtils.isIDCardNo(cardNo2)) {// 身份证
//                bindingResult.rejectValue("signUserIdCard", "{common.idcard.incorrect}");
//            } else if (contract.getCertificateType() == CertificateType.passport.getIndex()
//                    && false == RegularCheckUtils.isPassport(cardNo2)) {// 护照
//                bindingResult.rejectValue("signUserIdCard", "{common.passport.incorrect}");
//            } else if (contract.getCertificateType() == CertificateType.MTPS.getIndex()
//                    && false == RegularCheckUtils.isTBCard(cardNo2)) {// 台胞证
//                bindingResult.rejectValue("signUserIdCard", "{common.tbcard.incorrect}");
//            } else if (contract.getCertificateType() == CertificateType.HKMACAOPASS.getIndex()
//                    && false == RegularCheckUtils.isHKMT(cardNo2)) {// 港澳台通行证
//                bindingResult.rejectValue("signUserIdCard", "{common.hkmt.incorrect}");
//            }
//        }
//
//        // 验证签约人信息
//        if (null != contract.getSignWithOwner() && !contract.getSignWithOwner()) {
//            // contract.getSignUserName();//签约人
//            // contract.getSignUserIdCard();//签约人证件号
//            // contract.getSignUserMobile();//签约人手机号
//            // contract.getOwnerName();//业主姓名
//            // contract.getOwnerIdCard();//业主证件号
//            // contract.getOwnerMobile();//业主手机号
//            if (!contract.getSignUserName().equals(contract.getOwnerName())) {
//                bindingResult.rejectValue("signUserName", "{common.sfSignWithOwner.check}");
//            }
//            if (!contract.getSignUserIdCard().equals(contract.getOwnerIdCard())) {
//                bindingResult.rejectValue("signUserIdCard", "{common.sfSignWithOwner.check}");
//            }
//            if (!contract.getSignUserMobile().equals(contract.getOwnerMobile())) {
//                bindingResult.rejectValue("signUserMobile", "{common.sfSignWithOwner.check}");
//            }
//        }
//
//        // 持卡人身份证件校验
//        String cardNo3 = contract.getBankUserIdCard();
//        if (!StringUtils.isEmpty(cardNo3)) {
//            if (contract.getCertificateType() == CertificateType.IDCARD.getIndex()
//                    && false == RegularCheckUtils.isIDCardNo(cardNo3)) {// 身份证
//                bindingResult.rejectValue("bankUserIdCard", "{common.idcard.incorrect}");
//            }
//        }
//        // 校验业主手机号
//        if (!StringUtils.isEmpty(contract.getOwnerMobile())) {
//            if (false == PhoneFormatCheckUtils.isPhoneLegal(contract.getOwnerMobile())) {
//                bindingResult.rejectValue("ownerMobile", "{common.mobile.format.fail}");
//            }
//        }
//        // 校验签约人手机号
//        if (!StringUtils.isEmpty(contract.getSignUserMobile())) {
//            if (false == PhoneFormatCheckUtils.isPhoneLegal(contract.getSignUserMobile())) {
//                bindingResult.rejectValue("signUserMobile", "{common.mobile.format.fail}");
//            }
//        }
//        // 校验紧急联系电话
//        if (!StringUtils.isEmpty(contract.getSignUserEmergencyPhone())) {
//            if (false == PhoneFormatCheckUtils.isPhoneLegal(contract.getSignUserEmergencyPhone())) {
//                bindingResult.rejectValue("signUserEmergencyPhone", "{common.mobile.format.fail}");
//            }
//        }
//
//        // 租约期限
//        if (contract.getStartDate() != null && contract.getEndDate() != null) {
//            // 开始日期必须不能小于当前日期
//            if (contract.getStartDate().getTime() >= contract.getEndDate().getTime()) {
//                bindingResult.rejectValue("startDate", "{cfcontract.rent_term.error2}");
//            }
//        }
//
//        // 校验非空选项弹出信息
//        if (bindingResult.hasErrors()) {
//            return R.fail(bindingResult);
//        } else {
//            return R.ok();
//        }
//    }
//
//
//    /**
//     * 根据合同租约信息生成相应账期的付款计划信息
//     *
//     * @param contract
//     * @return
//     * @throws ParseException
//     */
//    @RequestMapping("generatePayMentPlan")
//    @ResponseBody
//    private Object generatePayMentPlan(contract contract) throws ParseException {
//        // 计算生成各账期付款计划
//        CalculateFkPlanForm dataPlan = new CalculateFkPlanForm();
//        BeanUtils.copy(contract, dataPlan);
//        dataPlan.setMonthRent(new BigDecimal(contract.getMonthRent()));// 收房月租金
//        dataPlan.setDepositMoney(new BigDecimal(contract.getDepositMoney()));// 房产押金
//        List<CwPaymentPlanDto> payMentPlanList = PayMentPlanGenerator.generatePayMentPlan(dataPlan);
////        ModelAndView mv = ModelAndViewUtil.of("shoufang/tempPayMentPlanList");
////        mv.addObject("payMentPlanList", payMentPlanList);
////        BigDecimal totalDeposit = new BigDecimal(contract.getDepositMoney())
////                .multiply(new BigDecimal(contract.getDepositType()));
////        if (BigDecimal.ZERO.equals(totalDeposit)) {
////            // 无押金
////            mv.addObject("hasDeposit", 0);
////        } else {
////            // 有押金
////            mv.addObject("hasDeposit", 1);
////        }
////        if (null != contract.getLastContractId()) {
////            mv.addObject("isXuYue", 1);// 续约(续约时自动生成的是已付的付款单，支付状态不可编辑)
////        } else {
////            mv.addObject("isXuYue", 0);
////        }
////        // 合同总金额
////        BigDecimal totalAmount = BigDecimal.ZERO;
////        for (CwPaymentPlanDto cwPaymentPlanDto : payMentPlanList) {
////            totalAmount = totalAmount.add(cwPaymentPlanDto.getPaymentAmount());
////        }
////        mv.addObject("totalAmount", totalAmount);
////        mv.addObject("preCycleChange", 0);
//        return null;
//    }
//
//
//
//
//
//    /**
//     * @param @param  contract
//     * @param @param  bindingResult
//     * @param @return 参数
//     * @return 返回值说明
//     * @throws Exception
//     * @Description: 保存收房合同
//     */
//    @RequestMapping("saveSfContract")
//    @ResponseBody
//    private R saveSfContract(@Validated contract contract)
//            throws Exception {
//        RequestDetailSfContractSaveDto requestDetailSfContractSaveDto = new RequestDetailSfContractSaveDto();
//        BeanUtils.copyProperties(contract, requestDetailSfContractSaveDto);
//        requestDetailSfContractSaveDto.setDepositMoney(new BigDecimal(contract.getDepositMoney()));
//        requestDetailSfContractSaveDto.setMonthRent(new BigDecimal(contract.getMonthRent()));
//        requestDetailSfContractSaveDto.setHouseName(contract.getHouseInfo());
//        requestDetailSfContractSaveDto.setLeaseStartTime(contract.getStartDate());
//        requestDetailSfContractSaveDto.setLeaseEndTime(contract.getEndDate());
////        sfContractService.saveSfContract(requestDetailSfContractSaveDto);
//        return R.ok();
//    }


    /**
     * 查询身份证信息
     */
    @RequiresPermissions("contract:contract:findIdcard")
    @GetMapping("/findIdcard")
    public R findIdcard(String url) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("api_key", "srXiN-r9iHJJcqCUX612rkLdHElAdTeg");
        map.put("api_secret", "WU9EJaL9uvnlCCsAWgkGJdVWvKIZ6wIP");
        map.put("image_url", url);
        String post = HttpUtil.post("https://api-cn.faceplusplus.com/cardpp/v1/ocridcard", map);
        JSONObject object = JSONUtil.parseObj(post);
        Object cards = object.get("cards");
        System.err.println(cards);
        return R.ok(cards);
    }

    /**
     * 查询收房合同列表
     */
    @RequiresPermissions("contract:contract:list")
    @GetMapping("/list")
    public TableDataInfo list(Contract contract) {
        startPage();
        List<Contract> list = contractService.selectContractList(contract);
        return getDataTable(list);
    }

    /**
     * 导出收房合同列表
     */
    @RequiresPermissions("contract:contract:export")
    @Log(title = "收房合同", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Contract contract) {
        List<Contract> list = contractService.selectContractList(contract);
        ExcelUtil<Contract> util = new ExcelUtil<Contract>(Contract.class);
        util.exportExcel(response, list, "收房合同数据");
    }

    /**
     * 获取收房合同详细信息
     */
    @RequiresPermissions("contract:contract:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(contractService.selectContractById(id));
    }

    /**
     * 新增收房合同
     */
//    @RequiresPermissions("contract:contract:add")
//    @Log(title = "收房合同", businessType = BusinessType.INSERT)
////    @PostMapping
//    public AjaxResult add(@RequestBody Contract contract) {
//
//        return toAjax(contractService.insertContract(contract));
//    }

    @Resource
    RedisService redisService;

    /**
     * 新增收房合同
     */
    @RequiresPermissions("contract:contract:contracttest")
    @Log(title = "收房合同", businessType = BusinessType.INSERT)
    @RequestMapping("contracttest")
    public R contracttest(@RequestBody Contract contract) {
        // 验证签约人信息
        if (null != contract.getSignWithOwner()) {
            if (!contract.getSignUserName().equals(contract.getOwnerName())) {
                new ServiceException(String.format("校验签约人名称"));
            }
            if (!contract.getSignUserIdCard().equals(contract.getOwnerIdCard())) {
                new ServiceException(String.format("校验签约人身份证号"));
            }
            if (!contract.getSignUserMobile().equals(contract.getOwnerMobile())) {
                new ServiceException(String.format("校验签约人手机号"));
            }
        }

        // 校验业主手机号
        if (!StringUtils.isEmpty(contract.getOwnerMobile())) {
            if (false == PhoneFormatCheckUtils.isPhoneLegal(contract.getOwnerMobile())) {
                new ServiceException(String.format("校验业主手机号"));
            }
        }
        // 校验签约人手机号
        if (!StringUtils.isEmpty(contract.getSignUserMobile())) {
            if (false == PhoneFormatCheckUtils.isPhoneLegal(contract.getSignUserMobile())) {
                new ServiceException(String.format("校验签约人手机号"));
            }
        }
        // 校验紧急联系电话
        if (!StringUtils.isEmpty(contract.getSignUserEmergencyPhone())) {
            if (false == PhoneFormatCheckUtils.isPhoneLegal(contract.getSignUserEmergencyPhone())) {
                new ServiceException(String.format("校验紧急联系电话"));
            }
        }

        // 租约期限
        if (contract.getLeaseStartTime() != null && contract.getLeaseEndTime() != null) {
            // 开始日期必须不能小于当前日期
            if (contract.getLeaseStartTime().getTime() >= contract.getLeaseEndTime().getTime()) {
                new ServiceException(String.format("开始日期必须不能小于当前日期"));
            }
        }
        Snowflake snowflake = new Snowflake();
        contract.setSfContractNo("SFHT" + snowflake.nextIdStr());
        contract.setConInfoTime(new Date());
        contract.setConAudTime(new Date());
        contract.setSignUserMobile(contract.getOwnerMobile());
        return R.ok(contract);
    }


    /**
     * 新增收房合同
     */
    @RequiresPermissions("contract:contract:contractAdd")
    @Log(title = "收房合同", businessType = BusinessType.INSERT)
    @RequestMapping("contractAdd")
    public AjaxResult contractAdd(@RequestBody Contract contract) {
        Boolean absent = redisService.redisTemplate.opsForValue().setIfAbsent(SecureUtil.md5(contract.toString()), 1, 2, TimeUnit.MINUTES);
        if (!absent) {
            new ServiceException(String.format("禁止重复提交"));
        }
        return toAjax(contractService.insertContract(contract));
    }


    /**
     * 新增收房合同
     */
    @RequiresPermissions("contract:contract:handleout")
    @Log(title = "收房合同", businessType = BusinessType.INSERT)
    @RequestMapping("handleout")
    public AjaxResult handleout(@RequestBody Contract contract) throws IOException, TemplateException {

        //创建配置对象
        Configuration configuration = new Configuration(Configuration.getVersion());
        //设置默认生成文件编码
        configuration.setDefaultEncoding("utf-8");
        //设置模板路径
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");
        //获取模板
        Template template = configuration.getTemplate("index.ftl");
        //加载数据========================================
        Map<String, Object> dataModel = new HashMap<String, Object>();
        dataModel.put("ownerName", contract.getOwnerName());
        dataModel.put("signUserName", contract.getSignUserName());
        dataModel.put("signUserIdCard", contract.getSignUserIdCard());
        dataModel.put("ownerIdCard", contract.getOwnerIdCard());
        dataModel.put("ownerContactAddress", contract.getOwnerContactAddress());
        dataModel.put("leaseStartTime", contract.getLeaseStartTime());
        dataModel.put("leaseEndTime", contract.getLeaseEndTime());
        dataModel.put("depositType", contract.getDepositType());
        dataModel.put("paymentType", contract.getPaymentType());
        dataModel.put("monthRent", contract.getMonthRent());
        BigDecimal rent = contract.getMonthRent();
        BigDecimal yajin = rent.multiply(BigDecimal.valueOf(contract.getPaymentType()));
        dataModel.put("sumPrice", yajin);
        dataModel.put("leaseStartTime", contract.getLeaseStartTime());
        dataModel.put("leaseEndTime", contract.getLeaseEndTime());
        dataModel.put("depositMoney", contract.getDepositMoney().multiply(BigDecimal.valueOf(contract.getDepositType())));
        //这个相当于从数据库查询出来的列表
//        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//        Map<String, Object> map1 = new HashMap<String, Object>();
//        map1.put("name", "苹果");
//        map1.put("price", 4.5);
//        Map<String, Object> map2 = new HashMap<String, Object>();
//        map2.put("name", "香蕉");
//        map2.put("price", 6.3);
//        list.add(map1);
//        list.add(map2);

//        dataModel.put("goodsList", list);
//        dataModel.put("today", new Date());
//        dataModel.put("number", 123456789L);

        //========================================
        Snowflake snowflake = new Snowflake();
        String s = snowflake.nextIdStr();
        //创建输出对象,将文件输出到D盘根目录下
        String word = "D:/upload/收房" + s + ".doc";
        FileWriter fileWriter = new FileWriter(word);
        //渲染模板和数据
        template.process(dataModel, fileWriter);
        //关闭输出
        fileWriter.close();

        contract.setReserve3(s + ".pdf");
        contractService.updateContract(contract);
        Doc2Pdf.doc2pdf(word, "D:/upload/aa" + s + ".pdf");
        return AjaxResult.success();
    }


    /**
     * 修改收房合同
     */
    @RequiresPermissions("contract:contract:edit")
    @Log(title = "收房合同", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Contract contract) {
        return toAjax(contractService.updateContract(contract));
    }

    /**
     * 删除收房合同
     */
    @RequiresPermissions("contract:contract:remove")
    @Log(title = "收房合同", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(contractService.deleteContractByIds(ids));
    }


    @Resource
    FinalStatementDetailService statementService;

    @Resource
    EmailUtil emailUtil;

    @Resource
    RocketMQTemplate rocketMQTemplate;

    /**
     * 修改收房合同
     */
    @RequiresPermissions("contract:contract:finalstatementAdd")
    @Log(title = "收房合同", businessType = BusinessType.INSERT)
    @RequestMapping("finalstatementAdd")
    public R finalstatementAdd(@RequestBody FinalStatement finalStatement) {
        Boolean absent = redisService.redisTemplate.opsForValue().setIfAbsent(SecureUtil.md5(finalStatement.toString()), 1, 2, TimeUnit.MINUTES);
        if (!absent) {
            new ServiceException(String.format("禁止重复提交"));
//            throw new RuntimeException();
        }
        System.err.println(finalStatement);
        finalStatement.setTSfTerminationId(finalStatement.getId());
        Snowflake snowflake = new Snowflake();
        String s = snowflake.nextIdStr();
        finalStatement.setSfTerminationNo("SFJY" + s);
//        finalStatement.setDealType(1);
//        finalStatement.setItemType(2);

        String email = finalStatement.getRemark();

        emailUtil.sendEmail(email, "解约成功");

//        rocketMQTemplate.asyncSend("myTest", email, new SendCallback() {
//            @Override
//            public void onSuccess(SendResult sendResult) {
//                System.err.println("发送成功");
//            }
//            @Override
//            public void onException(Throwable throwable) {
//                System.err.println("发送失败");
//            }
//        });

        boolean b = statementService.saveOrUpdate(finalStatement);
        if (b) {
            return R.ok();
        }
        return R.fail();
    }


}
